package com.hava.contentsale.web.controller.api;

import com.hava.contentsale.meta.UserVO;
import com.hava.contentsale.service.UserService;
import com.hava.contentsale.utils.web.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * Created by yanfa on 2016/11/16.
 * 异步数据接口 - 1. 登录
 * R2.1 用户登录时，需要输入用户名和密码，前端将密码用MD5加密后传输；
 * 说明：这里实施用户登录，接收用户名密码，并在session中记录，其他界面从session获取用户信息
 * 针对不同类型的错误进行响应。
 * 详细见文档
 * https://my.oschina.net/hava/blog/779440
 */
@Controller
@RequestMapping(value = "/api")
public class LoginApiController {

    @Autowired
    UserService userServiceImpl;

    @ResponseBody
    @RequestMapping(value = "/login",method= RequestMethod.POST,produces = MediaType.JSON)
    public JsonResult api_login(@RequestParam("userName") String username,
                                @RequestParam("password") String password,
                                HttpSession httpSession)
    {
        System.out.println("Class LoginApiController Method api_login");
        System.out.println("[username]:" + username);
        System.out.println("[password]:" + password);

        JsonResult jsonResult = new JsonResult();
        //TODO:username password 空值检测，想法是使用AOP+反射进行实现
        if(username == null && password == null)
        {
            //请求参数有错误 http status code is 400
            jsonResult.setCode("400");
            jsonResult.setMessage("登录失败");
            jsonResult.setResult(false);
        }
        else
        {
            System.out.println("[session]:" + httpSession.getId());
            UserVO userVO = this.userServiceImpl.getUser(username, password);

            if (userVO == null)
            {
                //根据http响应，需要响应401.1表示登陆失败
                jsonResult.setCode("401.1");
                //根据javascript上面所提示的内容进行，以便在界面上弹出登陆失败
                jsonResult.setMessage("登录失败");
                jsonResult.setResult(false);
            }
            else
            {
                //读取用户信息成功，写入session，并返回正确信息
                httpSession.setAttribute("user",userVO);

                jsonResult.setCode("200");
                jsonResult.setMessage("登陆成功");
                jsonResult.setResult(true);
            }
        }

        return jsonResult;
    }
}
